package com.icesoft.base.manager.service.manager;

import java.util.*;

import com.icesoft.core.web.suppose.setting.service.ISysSettingService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.icesoft.base.manager.base.BaseService;
import com.icesoft.core.dao.criteria.FromBuilder;
import com.icesoft.core.dao.criteria.QueryBuilder;
import com.icesoft.core.dao.criteria.SelectBuilder;
import com.icesoft.core.web.model.SysSettingDTO;
import com.icesoft.base.manager.entity.manager.SysSetting;

@Service
@CacheConfig(cacheNames = { SysSettingService.CACHE_GROUP })
public class SysSettingService extends BaseService<SysSetting> implements ISysSettingService {
	public static final String CACHE_GROUP = "sysSettingService";
	public static final String KEY_FIND_GROUPS = "'findGroups'";

	public SysSetting findByGroupAndName(String groupName, String keyName) {
		return unique(QueryBuilder.get("groupName", groupName).andEq("keyName", keyName));
	}

	@Override
	@Cacheable(key = "#groupName")
	public Map<String, String> findByGroup(String groupName) {
		List<SysSetting> list = find(QueryBuilder.get("groupName", groupName));
		Map<String, String> map = new HashMap<>();
		for (SysSetting sysSetting : list) {
			map.put(sysSetting.getKeyName(), sysSetting.getVal());
		}
		return Collections.unmodifiableMap(map);
	}

	@Cacheable(key = KEY_FIND_GROUPS)
	public List<String> findGroups() {
		List<String> groups = findSelect(SelectBuilder.select("groupName").builder(FromBuilder.get().distinct()));
		return Collections.unmodifiableList(groups);
	}

	@Override
	@Transactional
	public void createSettings(Collection<SysSettingDTO> sysSettingDTOs) {
		sysSettingDTOs.forEach(sysSettingDTO -> {
			SysSetting sysSetting = new SysSetting();
			sysSetting.setGroupName(sysSettingDTO.getGroupName());
			sysSetting.setKeyName(sysSettingDTO.getKeyName());
			sysSetting.setVal(sysSettingDTO.getVal());
			sysSetting.setDes(sysSettingDTO.getDes());
			create(sysSetting);
		});
	}

	@Override
	public void remove(String groupName, String keyName) {
		delete(findByGroupAndName(groupName, keyName));
	}

	public int remove(String groupName) {
		List<SysSetting> list = find(QueryBuilder.get("groupName", groupName));
		delete(list);
		return list.size();
	}
}
